<template>
  <div class="card">
    <div class="card-header flex content-space-between">
      <span>
        截止
        <el-tag type="warning" size="mini">{{ endTime }}</el-tag>
        ，近七天群组在
        <el-tag type="warning" size="mini">{{ relatedSpace }}</el-tag>
        的活跃统计（每两小时可重新获取）
      </span>
      <router-link :to="`/groups/${groupId}/activities`" class="link el-link--primary shrink-0">
        查看更多
      </router-link>
    </div>
    <div class="card-content flex text-center" v-loading="loading" style="min-height: 5.8rem;">
      <div class="flex-1">
        <h2>{{ isNum(docsCount) ? docsCount : '--' }}</h2>
        <p>创建资源</p>
      </div>
      <div class="flex-1">
        <h2>{{ isNum(issuesCount) ? issuesCount : '--' }}</h2>
        <p>提出问题</p>
      </div>
      <div class="flex-1">
        <h2>{{ isNum(commentsCount) ? commentsCount : '--' }}</h2>
        <p>评论回复</p>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { last7days } from '../../activities/date_time_picker_options';
import { formatActivities } from '../../../format';

export default {
  name: 'global-activities', // 群组活跃总况
  data() {
    return {
      docsCount: undefined,
      issuesCount: undefined,
      commentsCount: undefined,
      endTime: '...',
      loading: false,
    };
  },
  computed: {
    ...mapState({ curGroup: 'currentGroup' }),
    groupId() { return this.$route.params.groupId; },
    relatedSpace() {
      return this.curGroup.space.title
        ? `关联空间：${this.curGroup.space.title}`
        // : '全平台'; // 群组一对一绑定后，可能会延迟显示这部分内容
        : '--';
    },
  },
  created() { this.loadActivities(); },
  methods: {
    loadActivities() {
      this.loading = true;
      this.$api.groups.activities({
        groupId: this.groupId,
        daterange: last7days,
      }).then((res) => {
        if (res.data.wait) setTimeout(this.loadActivities, 2000);
        else {
          const result = formatActivities(res.data);
          this.docsCount = result.docsCount;
          this.issuesCount = result.issuesCount;
          this.commentsCount = result.commentsCount;
          this.endTime = result.endTime;
          this.loading = false;
        }
      }).catch(() => { this.loading = false; });
    },
    resetCounts() {
      this.docsCount = undefined;
      this.issuesCount = undefined;
      this.commentsCount = undefined;
    },
  },
  watch: {
    groupId() {
      this.resetCounts();
      this.loadActivities(); // 有正确值再请求
    },
  },
};
</script>

<style></style>
